/**
 * Copyright (c) 2017 ucsmy.com, All rights reserved.
 */
package itsm.isperp.module.controller.api.wechat.v2;

import itsm.isperp.framework.utils.Pair;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.project.ProjProject;
import itsm.isperp.module.entity.task.TskTask;
import itsm.isperp.module.service.project.ProjProjectService;
import itsm.isperp.module.service.task.TskTaskService;
import itsm.isperp.workflow.dto.BpmTransitionLine;
import itsm.isperp.workflow.service.BpmProcessRunService;
import itsm.isperp.workflow.utils.BpmConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: legen
 * @Created Date: 2017-09-14-0014.
 * @LastModifyDate: 2017-09-14-0014.
 * @LastModifyBy: legen
 * @Version:
 */
@Controller
@RequestMapping("api/wechat/v2/task")
public class TaskController extends BaseController {

    @Resource(name = "bpmProcessRunService")
    private BpmProcessRunService bpmProcessRunService;

    @Autowired
    private TskTaskService taskService;

    @Autowired
    private ProjProjectService projProjectService;

    /**
     * 查询任务数量
     */
    @RequestMapping("countByStatus")
    @ResponseBody
    public List<Map<String, Object>> countByStatus(String username)
            throws Exception {
        JqGridRequest request = new JqGridRequest();
        request.setSelectColumns("COUNT(*) count", "status", "CASE status WHEN '待处理' THEN 0 WHEN '重新分派' THEN 1 WHEN '任务确认' THEN 2 END order_no");
        request.setSearchString(BpmConst.getQueryTaskSqlCondition(TASK_PROCESS, "'" + username + "'") + " and  status in('待处理','重新分派','任务确认')");
        request.setGroupBy("status");
        request.setSort("order_no", Sort.Direction.ASC);

        List<Map<String, Object>> count = taskService.findAllDetailByRequest(request);
        return count;
    }

    /**
     * 查询事件
     */
    @RequestMapping("listByStatus")
    @ResponseBody
    public List<Map<String, Object>> listByStatus(String username, String status)
            throws Exception {
        JqGridRequest request = new JqGridRequest();
        request.setPageable(false);
        request.setSelectColumns("id", "name", "plan_start_time", "task_type", "creator_name", "status");
        request.setSort("plan_start_time", Sort.Direction.ASC);
        request.setSearchString(BpmConst.getQueryTaskSqlCondition(TASK_PROCESS, "'" + username + "'") + " and  status = '" + status + "'");

        List<Map<String, Object>> list = taskService.findAllDetailByRequest(request).getContent();
        super.addNullColumns(request, list);
        return list;
    }

    /**
     * 任务明细
     */
    @RequestMapping("detail")
    @ResponseBody
    public BpmData<TskTask> detail(String username, String id)
            throws Exception {
        JqGridRequest request = new JqGridRequest();
        request.setSelectColumns(
                "id", "process_id", "status", "task_type",
                "code", "name", "project_id", "project_stage", "priority",
                "plan_principal_id", "plan_principal_name", "plan_start_time", "plan_end_time", "plan_times",
                "target", "content", "deliverables",
                "finished", "act_start_time", "act_end_time", "act_times", "act_principal_id", "act_principal_name", "handle_desc"
        );
        request.addFilterRule("id", JqGridFilterRuleOp.eq, id);
        TskTask data = taskService.findOneByRequest(request);

        if (data != null) {

            BpmData<TskTask> model = new BpmData<>();
            model.setData(data);
            model.setOthers(new HashMap<String,Object>());

            List<BpmTransitionLine> lines = bpmProcessRunService.getNextSteps(TASK_PROCESS, data.getProcessId(), username);
            model.setLines(lines);

            ProjProject project = projProjectService.findOne(data.getProjectId());
            if (project != null) {
                model.getOthers().put("projectName", project.getName());
            }

            return model;

        } else {

            throw new Exception("该任务已删除!");
        }
    }

    @RequestMapping(value = "submit", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> submit(String username, @RequestBody BpmData<TskTask> model)
            throws Exception {
        login(username);

        this.taskService.saveOrUpdateSpecific(model.getData(), model.getColumns());
        TskTask data = model.getData();
        BpmTransitionLine line = model.getLine();

        Pair<String, List<Map<String, Object>>> result = this.bpmProcessRunService
                .gotoNextSetp(
                        username,
                        TASK_PROCESS,
                        line.getNextTaskId(),
                        line.getNextTransitionId(),
                        line.getProcessInstanceId(),
                        data.getId(),
                        model.getNextAssigner(),
                        model.getSuggestion(),
                        line.getProcessMode(),
                        line.getCommitType());

        uploadPositionInfo(username, (String) model.getOthers().get("longitude"), (String) model.getOthers().get("latitude"));

        Map<String, Object> nextStep = new HashMap<>();
        if (result == null || result.getRightObject() == null || result.getRightObject().size() == 0) {
            nextStep.put("message", "流程结束");
            return nextStep;
        }

        StringBuilder nextUser = new StringBuilder();
        List<Map<String, Object>> list = result.getRightObject();
        int i = list.size();
        if (i > 0) {
            nextUser.append(list.get(0).get("fullname")).append("(").append(list.get(0).get("name")).append(")");
        }
        for (int j = 1; j < i; j++) {
            Map<String, Object> m = list.get(j);
            if (m != null) {
                nextUser.append(",").append(m.get("fullname")).append("(").append(m.get("name")).append(")");
            }
        }

        nextStep.put("message", result.getLeftObject() + "：" + nextUser.toString());
        return nextStep;
    }
}
